package com.rxz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rxz.common.ShopCommon;
import com.rxz.dao.OrdersDao;
import com.rxz.dao.ShopDao;
import com.rxz.entity.Orders;
import com.rxz.entity.Result;
import com.rxz.entity.Shop;
import com.rxz.service.ShopService;
import com.rxz.utils.ResultUtil;
import com.rxz.utils.SimpleRedisLock;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopDao, Shop> implements ShopService {

    @Resource
    private RedisTemplate redisTemplate;


    @Autowired
    private OrdersDao ordersDao;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result isEndTime(Integer id,Integer userId) {
        QueryWrapper<Shop> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Shop shop_info = getOne(wrapper);

        Timestamp startTime = Timestamp.valueOf(shop_info.getStartTime());
        Timestamp endTime = Timestamp.valueOf(shop_info.getEndTime());
        if(endTime.compareTo(startTime) < 0){
            return ResultUtil.error(401,"活动时间已经过去！");
        }
        Timestamp nowTime = new Timestamp(System.currentTimeMillis());
        if (nowTime.compareTo(startTime) < 0){
            return ResultUtil.error(401,"活动还没开始！");
        }
        if(shop_info.getStock() < 1){
            return ResultUtil.error(401,"库存不足！");
        }
        UpdateWrapper<Shop> upWrapper = new UpdateWrapper<>();
        upWrapper.eq("id", id).setSql("stock = stock - 1").setSql("version = version + 1");
        boolean isUpdate = this.update(upWrapper);
//        boolean isUpdate = this.update(upWrapper.setSql("stock = stock - 1,version = version + 1"));
        if (!isUpdate){
            return ResultUtil.error(401,"库存不足！");
        }

        // 创建一个订单id
        String orderId = ShopCommon.ORDER_ID_KEY + String.valueOf(System.currentTimeMillis());
        //创建redis分布式锁 代替悲观锁
        SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
        boolean isLock = lock.tryLock(5);
        if(!isLock) {
            //获取锁失败
            return ResultUtil.error(401,"下单失败！");
        }else {
            System.out.println("获取锁资源成功，锁是：" + lock);
            stringRedisTemplate.opsForValue().set("syc","order:" + userId,5L,TimeUnit.SECONDS);
        }
        Orders orders = new Orders();
        try {
            orders.setOrderId(orderId);
            orders.setUserId(userId);
            ordersDao.insert(orders);
            redisTemplate.opsForValue().set(orderId,orders,30L, TimeUnit.SECONDS);
        }finally {
            lock.unlock();
        }
//        int save = ordersDao.insert(orders);
//        if (save < 0){
//            return ResultUtil.error(401,"添加对象失败");
//        }
        return ResultUtil.success(orders);
    }

    public Result isOrderTrue(String orderId){
        Object orders = redisTemplate.opsForValue().get(orderId);
        if (orders == null){
            return ResultUtil.error(401,"订单过期！");
        }
        return ResultUtil.success(orders);
    }
}
